package com.toy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.toy.entity.User;
import com.toy.entity.UserRole;
import com.toy.exception.ToyMallException;
import com.toy.form.UserLoginForm;
import com.toy.form.UserRegisterForm;
import com.toy.mapper.OrderDetailMapper;
import com.toy.mapper.OrdersMapper;
import com.toy.mapper.UserMapper;
import com.toy.mapper.UserRoleMapper;
import com.toy.result.ResponseEnum;
import com.toy.service.AdminService;
import com.toy.util.MD5Util;
import com.toy.util.RegexValidateUtil;
import com.toy.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author tystart
 * @create 2022-09-08-9:16
 */
@Service
@Slf4j
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public String findUserByUp(UserLoginForm userLoginForm) {
        //判断用户名是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", userLoginForm.getLoginName());
        User user = this.userMapper.selectOne(queryWrapper);

        if (user == null){
            log.info("【管理员登录】用户名不存在");
            return null;
        }
        //判断密码是否正确
        boolean saltverifyMD5 = MD5Util.getSaltverifyMD5(userLoginForm.getPassword(), user.getPassword());
        if (!saltverifyMD5){
            log.info("【管理员登录】密码错误");
            return null;
        }
        //判断是否有权限
        UserRole userRole = this.userRoleMapper.selectById(user.getId());
        if (userRole.getRole() != 1){
            log.info("【管理员登录】没有权限");
            return null;
        }
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public PageResult findUserByPage(PageResult pageResult) {
        // 定义分页对象，封装2个参数 public Page(long current, long size)
        IPage<User> page = new Page<>(pageResult.getPageNum(),
                pageResult.getPageSize());
        // 定义查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "login_name", pageResult.getQuery());

        // 根据传入的分页条件，和查询条件，获得 分页结果数据
        //   （4个参数：current size total records查询记录的结果）
        page = userMapper.selectPage(page, queryWrapper);


        // 封装结果
        List<User> userList = page.getRecords(); //获得查询记录的结果
        pageResult.setTotal(page.getTotal());
        for (User user : userList) {
            user.setRole(userRoleMapper.selectById(user.getId()).getRole()==1);
        }
        pageResult.setRows(userList);

        return pageResult;
    }

    @Override
    public void updateRole(User user) {
        UserRole userRole = new UserRole();
        userRole.setId(user.getId());
        userRole.setRole(user.getRole()?1:0);
        userRoleMapper.updateById(userRole);
    }

    @Override
    public void addUser(UserRegisterForm userRegisterForm) {
        //用户名是否可用
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", userRegisterForm.getLoginName());
        User one = this.userMapper.selectOne(queryWrapper);
        if (one != null){
            log.info("【添加用户】用户名已存在");
            throw new ToyMallException(ResponseEnum.MOBILE_ERROR);
        }

        //邮箱格式校验
        if (!RegexValidateUtil.checkEmail(userRegisterForm.getEmail())){
            log.info("【添加用户】邮箱格式错误");
            throw new ToyMallException(ResponseEnum.EMAIL_ERROR);
        }
        //手机格式校验
        if (!RegexValidateUtil.checkMobile(userRegisterForm.getMobile())){
            log.info("【添加用户】手机格式错误");
            throw new ToyMallException(ResponseEnum.Phone_ERROR);
        }
        //存储数据
        User user = new User();
        user.setFileName("3.jpg");
        //BeanUtils复制属性
        BeanUtils.copyProperties(userRegisterForm, user);
        user.setPassword(MD5Util.getSaltMD5(user.getPassword()));
        user.setRole(false);
        int insert = this.userMapper.insert(user);
        UserRole userRole = new UserRole();
        userRole.setRole(0);
        userRole.setId(user.getId());
        this.userRoleMapper.insert(userRole);
        if (insert != 1){
            log.info("【添加用户】添加用户失败");
            throw new ToyMallException(ResponseEnum.USER_REGISTER_ERROR);
        }
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteById(id);
        userRoleMapper.deleteById(id);
    }

    @Override
    public void updateU(User user) {
        user.setPassword(MD5Util.getSaltMD5(user.getPassword()));
        userMapper.updateById(user);
    }
}
